package com.cencat.route.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencat.route.entity.Merchant;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 商户信息数据访问层
 * 提供商户信息的数据库操作接口
 * 
 * @author cencat
 * @version 1.0
 * @since 2024-01-01
 */
@Mapper
public interface MerchantMapper extends BaseMapper<Merchant> {

    /**
     * 分页查询商户信息
     */
    Page<Merchant> selectMerchantPage(Page<Merchant> page, @Param("merchantCode") String merchantCode, 
                                     @Param("merchantName") String merchantName, @Param("status") String status,
                                     @Param("merchantType") String merchantType);

    /**
     * 条件查询商户信息
     */
    List<Merchant> searchMerchants(@Param("conditions") Map<String, Object> conditions);

    /**
     * 根据商户编号查询商户
     */
    @Select("SELECT * FROM merchant WHERE merchant_code = #{merchantCode} AND deleted = 0")
    Merchant selectByMerchantCode(@Param("merchantCode") String merchantCode);

    /**
     * 根据商户名称查询商户
     */
    @Select("SELECT * FROM merchant WHERE merchant_name = #{merchantName} AND deleted = 0")
    Merchant selectByMerchantName(@Param("merchantName") String merchantName);

    /**
     * 根据联系电话查询商户
     */
    @Select("SELECT * FROM merchant WHERE contact_phone = #{contactPhone} AND deleted = 0")
    Merchant selectByContactPhone(@Param("contactPhone") String contactPhone);

    /**
     * 根据营业执照号查询商户
     */
    @Select("SELECT * FROM merchant WHERE business_license = #{businessLicense} AND deleted = 0")
    Merchant selectByBusinessLicense(@Param("businessLicense") String businessLicense);

    /**
     * 根据状态查询商户列表
     */
    @Select("SELECT * FROM merchant WHERE status = #{status} AND deleted = 0")
    List<Merchant> selectByStatus(@Param("status") String status);

    /**
     * 根据商户类型查询商户列表
     */
    @Select("SELECT * FROM merchant WHERE merchant_type = #{merchantType} AND deleted = 0")
    List<Merchant> selectByMerchantType(@Param("merchantType") String merchantType);

    /**
     * 根据地区查询商户列表
     */
    @Select("SELECT * FROM merchant WHERE province = #{province} AND city = #{city} AND deleted = 0")
    List<Merchant> selectByRegion(@Param("province") String province, @Param("city") String city);

    /**
     * 批量更新商户状态
     */
    @Update("<script>" +
            "UPDATE merchant SET status = #{status}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("ids") List<Long> ids, @Param("status") String status);

    /**
     * 批量更新商户信用等级
     */
    @Update("<script>" +
            "UPDATE merchant SET credit_level = #{creditLevel}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateCreditLevel(@Param("ids") List<Long> ids, @Param("creditLevel") String creditLevel);

    /**
     * 批量更新商户服务费率
     */
    @Update("<script>" +
            "UPDATE merchant SET service_rate = #{serviceRate}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateServiceRate(@Param("ids") List<Long> ids, @Param("serviceRate") BigDecimal serviceRate);

    /**
     * 批量更新商户结算周期
     */
    @Update("<script>" +
            "UPDATE merchant SET settlement_cycle = #{settlementCycle}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateSettlementCycle(@Param("ids") List<Long> ids, @Param("settlementCycle") Integer settlementCycle);

    /**
     * 获取商户统计分析
     */
    Map<String, Object> getMerchantStatistics(@Param("startTime") LocalDateTime startTime, 
                                             @Param("endTime") LocalDateTime endTime);

    /**
     * 商户信用评估
     */
    Map<String, Object> evaluateMerchantCredit(@Param("merchantId") Long merchantId, 
                                              @Param("evaluationPeriod") Integer evaluationPeriod);

    /**
     * 商户业务分析
     */
    Map<String, Object> analyzeMerchantBusiness(@Param("merchantId") Long merchantId, 
                                               @Param("startTime") LocalDateTime startTime, 
                                               @Param("endTime") LocalDateTime endTime);

    /**
     * 查询活跃商户
     */
    @Select("SELECT * FROM merchant WHERE status = 'ACTIVE' AND deleted = 0 ORDER BY last_order_time DESC")
    List<Merchant> selectActiveMerchants();

    /**
     * 查询待审核商户
     */
    @Select("SELECT * FROM merchant WHERE status = 'PENDING' AND deleted = 0 ORDER BY created_time ASC")
    List<Merchant> selectPendingMerchants();

    /**
     * 查询已认证商户
     */
    @Select("SELECT * FROM merchant WHERE verified = 1 AND deleted = 0")
    List<Merchant> selectVerifiedMerchants();

    /**
     * 查询未认证商户
     */
    @Select("SELECT * FROM merchant WHERE verified = 0 AND deleted = 0")
    List<Merchant> selectUnverifiedMerchants();

    /**
     * 查询停用商户
     */
    @Select("SELECT * FROM merchant WHERE status = 'INACTIVE' AND deleted = 0")
    List<Merchant> selectInactiveMerchants();

    /**
     * 检查商户是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM merchant WHERE merchant_code = #{merchantCode} AND deleted = 0")
    boolean checkMerchantExists(@Param("merchantCode") String merchantCode);

    /**
     * 商户注册
     */
    int registerMerchant(@Param("merchant") Map<String, Object> merchant);

    /**
     * 商户认证
     */
    @Update("UPDATE merchant SET verified = 1, verified_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int verifyMerchant(@Param("id") Long id);

    /**
     * 商户激活
     */
    @Update("UPDATE merchant SET status = 'ACTIVE', activated_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int activateMerchant(@Param("id") Long id);

    /**
     * 商户停用
     */
    @Update("UPDATE merchant SET status = 'INACTIVE', deactivated_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int deactivateMerchant(@Param("id") Long id);

    /**
     * 商户冻结
     */
    @Update("UPDATE merchant SET status = 'FROZEN', frozen_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int freezeMerchant(@Param("id") Long id);

    /**
     * 商户解冻
     */
    @Update("UPDATE merchant SET status = 'ACTIVE', unfrozen_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int unfreezeMerchant(@Param("id") Long id);

    /**
     * 更新商户信用分数
     */
    @Update("UPDATE merchant SET credit_score = #{creditScore}, updated_time = NOW() WHERE id = #{id}")
    int updateCreditScore(@Param("id") Long id, @Param("creditScore") BigDecimal creditScore);

    /**
     * 更新商户余额
     */
    @Update("UPDATE merchant SET balance = #{balance}, updated_time = NOW() WHERE id = #{id}")
    int updateBalance(@Param("id") Long id, @Param("balance") BigDecimal balance);

    /**
     * 更新商户最后订单时间
     */
    @Update("UPDATE merchant SET last_order_time = #{lastOrderTime}, updated_time = NOW() WHERE id = #{id}")
    int updateLastOrderTime(@Param("id") Long id, @Param("lastOrderTime") LocalDateTime lastOrderTime);

    /**
     * 获取商户收入统计
     */
    Map<String, Object> getMerchantIncomeStatistics(@Param("merchantId") Long merchantId, 
                                                   @Param("startTime") LocalDateTime startTime, 
                                                   @Param("endTime") LocalDateTime endTime);

    /**
     * 获取商户订单统计
     */
    Map<String, Object> getMerchantOrderStatistics(@Param("merchantId") Long merchantId, 
                                                  @Param("startTime") LocalDateTime startTime, 
                                                  @Param("endTime") LocalDateTime endTime);

    /**
     * 获取商户评分统计
     */
    Map<String, Object> getMerchantRatingStatistics(@Param("merchantId") Long merchantId);

    /**
     * 根据时间范围查询商户
     */
    List<Merchant> selectByTimeRange(@Param("startTime") LocalDateTime startTime, 
                                    @Param("endTime") LocalDateTime endTime);

    /**
     * 根据信用分数范围查询商户
     */
    List<Merchant> selectByCreditScoreRange(@Param("minScore") BigDecimal minScore, 
                                           @Param("maxScore") BigDecimal maxScore);

    /**
     * 根据余额范围查询商户
     */
    List<Merchant> selectByBalanceRange(@Param("minBalance") BigDecimal minBalance, 
                                       @Param("maxBalance") BigDecimal maxBalance);

    /**
     * 查询高信用商户
     */
    @Select("SELECT * FROM merchant WHERE credit_score >= 80 AND deleted = 0 ORDER BY credit_score DESC")
    List<Merchant> selectHighCreditMerchants();

    /**
     * 查询低信用商户
     */
    @Select("SELECT * FROM merchant WHERE credit_score < 60 AND deleted = 0 ORDER BY credit_score ASC")
    List<Merchant> selectLowCreditMerchants();

    /**
     * 查询VIP商户
     */
    @Select("SELECT * FROM merchant WHERE merchant_level = 'VIP' AND deleted = 0")
    List<Merchant> selectVipMerchants();

    /**
     * 查询新注册商户
     */
    @Select("SELECT * FROM merchant WHERE created_time >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND deleted = 0 ORDER BY created_time DESC")
    List<Merchant> selectNewMerchants();

    /**
     * 查询长期未活跃商户
     */
    @Select("SELECT * FROM merchant WHERE last_order_time < DATE_SUB(NOW(), INTERVAL 90 DAY) AND deleted = 0")
    List<Merchant> selectInactiveLongTermMerchants();

    /**
     * 查询附近商户
     */
    List<Merchant> selectNearbyMerchants(@Param("latitude") BigDecimal latitude, 
                                        @Param("longitude") BigDecimal longitude, 
                                        @Param("radius") BigDecimal radius);

    /**
     * 查询同行业商户
     */
    @Select("SELECT * FROM merchant WHERE industry = #{industry} AND deleted = 0")
    List<Merchant> selectSameIndustryMerchants(@Param("industry") String industry);

    /**
     * 商户等级升级
     */
    @Update("UPDATE merchant SET merchant_level = #{level}, level_updated_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int upgradeMerchantLevel(@Param("id") Long id, @Param("level") String level);

    /**
     * 商户等级降级
     */
    @Update("UPDATE merchant SET merchant_level = #{level}, level_updated_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int downgradeMerchantLevel(@Param("id") Long id, @Param("level") String level);

    /**
     * 获取商户合作统计
     */
    Map<String, Object> getMerchantCooperationStatistics(@Param("merchantId") Long merchantId, 
                                                        @Param("startTime") LocalDateTime startTime, 
                                                        @Param("endTime") LocalDateTime endTime);

    /**
     * 获取商户风险评估
     */
    Map<String, Object> getMerchantRiskAssessment(@Param("merchantId") Long merchantId);

    /**
     * 智能推荐合作商户
     */
    List<Merchant> intelligentRecommendMerchants(@Param("merchantId") Long merchantId, 
                                                @Param("conditions") Map<String, Object> conditions);

    /**
     * 商户数据导出
     */
    List<Map<String, Object>> exportMerchantData(@Param("conditions") Map<String, Object> conditions);

    /**
     * 商户合规性检查
     */
    Map<String, Object> checkMerchantCompliance(@Param("merchantId") Long merchantId);

    /**
     * 自动分配商户等级
     */
    String autoAssignMerchantLevel(@Param("merchantId") Long merchantId, @Param("conditions") Map<String, Object> conditions);
}